package com.siecom.transport.handler;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.widget.Toast;

import com.siecom.constconfig.ConstDefine;
import com.siecom.hostservice.HKBaseApplication;
import com.siecom.hostservice.MainActivity;
import com.siecom.module.DeviceInterface;
import com.siecom.proto.Message;
import com.siecom.tool.LogUtil;
import com.siecom.transport.CommServer;
import com.siecom.transport.SiecomDevice;
import com.siecom.transport.bluetooth.BlueServer;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by on 2017/2/4.
 */

public class OtherHandler implements ServiceHandler {
    private static final String TAG = OtherHandler.class.getSimpleName();
    private CommServer server;
    private static ExecutorService threadPool = Executors.newFixedThreadPool(1);
    public volatile  boolean flag = false;

    @Override
    public void onReceive(CommServer server, Message.siecomproto msg,String message) {
        this.server = server;
        switch (msg.getCmd()){
            case ConstDefine.DEVICE_SERIAL_NO_REQUEST:
                getDeviceId(msg);
                break;
            case ConstDefine.CODENAME_REQUEST:
                setCodeName(msg);
                break;
            case ConstDefine.GET_CODENAME_REQUEST:
                getCodeName(msg);
                break;
            case ConstDefine.RESET_REQUEST:
                reset(msg);
                break;

            case ConstDefine.START_LAUNCHER_REQUEST:

                startLauncher(msg);
                break;

            case ConstDefine.LIGHT_TEST_REQUEST:
                testLight(msg);
                break;

            case ConstDefine.PSAM_TEST_REQUEST:
//                testPsam(msg);
                break;
            case ConstDefine.SERIAL_TEST_REQUEST:

                testSerial(msg);

                break;

            case ConstDefine.CHANGE_BLUE_NAME:
                changeBlueName(msg);
                break;
            case ConstDefine.DISCONNECT_BLUE:
                LogUtil.e(TAG,"DISCONNECT_BLUE");
                disconnectBlue(msg);
                break;
            case ConstDefine.GET_BATTARY_INFO_REQUEST: //获取电池信息
                getBattaryInfo(msg);
                break;
            //检测各模块信息
            case ConstDefine.CHECK_MODULE_INFO_REQUEST:
                checkModules(msg);
                break;
            //
            case ConstDefine.GET_DEVICE_VERSION_REQUEST:
                getDeviceHwVersion(msg);
                break;

            case ConstDefine.MAKE_BEEP_REQUEST:
                makeBeep(msg);
                break;

            case ConstDefine.MAKE_VOICE_REQUEST:
                makeVoice(msg);
                break;
        }
    }
    public void checkModules(Message.siecomproto msg ){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String inModule = "";
                String modules[] = null;
                String respond = "";
                try {
                    JSONObject jb = new JSONObject(msg.getRequest());
                    if(jb.has("moduleName")){
                        inModule = jb.getString("moduleName");
                    }else {
                        inModule = "";
                    }
                    if (inModule != null){
                        JSONObject outJson = new JSONObject();
                        if (inModule.contains(":"))
                             modules = inModule.split(":");
                        if (inModule.contains(","))
                            modules = inModule.split(",");
                        if (inModule.contains("，"))
                            modules = inModule.split("，");
                        outJson.put("state",0);
                        for (String mod : modules){

                            if(mod.equals("CR") || modules.length == 0){ //读卡器
                                outJson.put("CR",0);
                            }
                            if(mod.equals("FR")){ //指纹仪
                                outJson.put("FR",0);
                            }
                            if(mod.equals("SR")){ //签名板
                                outJson.put("SR",0);
                            }
                            if(mod.equals("MR")){ //磁条卡
                                outJson.put("MR",0);
                            }
                            if(mod.equals("PR")){ //密码键盘
                                outJson.put("PR",0);
                            }
                            if (mod.equals("IDC")){ //非接触式身份证读卡器
                                outJson.put("IDC",0);
                            }
                            if (mod.equals("ICC")){ //非接触式 IC 卡读卡器
                                outJson.put("ICC",0);
                            }
                            if (mod.equals("ICCX")){ //接触式 IC 卡读卡器
                                outJson.put("ICCX",0);
                            }
                        }
                        respond = outJson.toString();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.CHECK_MODULE_INFO_RESPOND);
                msgBuilder.setError(0);
                msgBuilder.setRespond(respond);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);
            }
        };
        threadPool.submit(runnable);
    }
    public void disconnectBlue(Message.siecomproto msg){
        LogUtil.e(TAG,"disconnectBlue");
//        SiecomDevice.closeBT();
        MainActivity.disconnectBlue();
//        HKBaseApplication.finishAllActivity();
//        HKBaseApplication.finishProgram();

    }

    public void changeBlueName(Message.siecomproto msg ){  //修改蓝牙名称
        Runnable runnable = new Runnable() {
            @Override
            public void run() {

                DeviceInterface.changeBlueName(msg.getRequest());
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.CHANGE_BLUE_NAME);
                msgBuilder.setError(0);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);
            }
        };
        threadPool.submit(runnable);
    }
    /**
     * 获取电池信息
     * @param msg
     */
    private void getBattaryInfo(Message.siecomproto msg){
        Runnable r = new Runnable() {
            @Override
            public void run() {
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.GET_BATTARY_INFO_RESPOND);
                msgBuilder.setError(0);
                msgBuilder.setRespond(MainActivity.mBattaryInfoJB.toString());
                LogUtil.e(TAG,"发送电池状态:" + MainActivity.mBattaryInfoJB.toString());
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);
            }
        };
        threadPool.submit(r);
    }

    public  void testSerial(Message.siecomproto msg){

    }
    public  void testLight(Message.siecomproto msg){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                int ledNum = Integer.parseInt(msg.getRequest());
                int onOff = Integer.parseInt(msg.getRespond());
                DeviceInterface.lightCtrl(ledNum,onOff);
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.LIGHT_TEST_RESPOND);
                msgBuilder.setError(0);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);

            }
        };

        threadPool.submit(runnable);

    }
    /**
     * 语音控制
     * @param msg 声音类型：
     * 0：请输入密码
     * 1：请再次输入密码
     * 2：密码错误，请重新输入密码
     * 3：请放置身份证
     * 4：请放置IC卡
     * 5：请插入IC卡
     * 6：请刷磁条卡
     * 7：请签字
     * 8：请录入指纹
     * 9：请重新录入指纹
     * a：操作成功
     */
    private void makeVoice(Message.siecomproto msg){
        Runnable r = new Runnable() {
            @Override
            public void run() {
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.MAKE_VOICE_RESPOND);
                msgBuilder.setError(0);
                int voiceType = Integer.parseInt(msg.getRequest());
                LogUtil.e(TAG,"voiceType ==" + voiceType);
                msgBuilder.setRespond(DeviceInterface.makeVoice(voiceType) + "" ); //语音控制
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);
            }
        };
        threadPool.submit(r);
    }
    /**
     * 蜂鸣声
     * @param msg
     */
    public  void makeBeep(Message.siecomproto msg){
        Runnable runnable = new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void run() {
                String message = msg.getRequest();
                int times = 1;
                int timeOut = 1000;
                try {
                    JSONObject jb = new JSONObject(message);
                    times = jb.getInt("times");
                    times = Integer.max(1,times);
                    timeOut = jb.getInt("timeout");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                DeviceInterface.makeBeep(times,timeOut);
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.MAKE_BEEP_RESPOND);
                msgBuilder.setError(0);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);

            }
        };

        threadPool.submit(runnable);

    }

    private void testPsam(Message.siecomproto msg){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                int tmp = Integer.valueOf(msg.getRequest());
                byte solt = 0x01;
                if(tmp==1){
                    solt = 0x01;
                }else if(tmp==2){
                    solt = 0x02;
                }
                int ret = DeviceInterface.testPsamSlot(solt);
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.PSAM_TEST_RESPOND);
                msgBuilder.setError(ret);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);

            }
        };

        threadPool.submit(runnable);


    }
    private void startLauncher(Message.siecomproto msg) {
        Runnable r = new Runnable() {
            @Override
            public void run() {

                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                ComponentName cn = new ComponentName("com.android.launcher3", "com.android.launcher3.Launcher");
                intent.setComponent(cn);
                MainActivity.context.startActivity(intent);

                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.START_LAUNCHER_RESPOND);
                msgBuilder.setError(0);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);

            }
        };
        threadPool.submit(r);
    }
    private void reset(Message.siecomproto msg) {
        Runnable r = new Runnable() {
            @Override
            public void run() {

                DeviceInterface.cancelFinancial();
                DeviceInterface.cancelIdentity();
                DeviceInterface.cancelFingerPrint();
//                DeviceInterface.cancelKeyBoardInput();

//                DeviceInterface.allClose();
//                DeviceInterface.allOpen();

                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.RESET_RESPOND);
                msgBuilder.setError(0);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);


            }
        };
        threadPool.submit(r);
    }

    public void getCodeName(Message.siecomproto msg){
        Runnable r = new Runnable() {
            @Override
            public void run() {
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.GET_CODENAME_RESPOND);
                msgBuilder.setError(0);
//                msgBuilder.setRespond(DeviceInterface.getValue("key"));
                msgBuilder.setRespond(DeviceInterface.getSerialCode());
                msgBuilder.setRequest(DeviceInterface.getDeviceId());

                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);

            }
        };
        threadPool.submit(r);


    }
    public  void setCodeName(Message.siecomproto msg){
        Runnable r = new Runnable() {
            @Override
            public void run() {
                DeviceInterface.setKeyValue("key",msg.getRequest());
                DeviceInterface.setSerialCode(msg.getRequest());  //写入SN编号
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.CODENAME_RESPOND);
                msgBuilder.setError(0);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);

            }
        };
        threadPool.submit(r);

    }
   public void getDeviceId(Message.siecomproto msg){

       Runnable r = () -> {
           String deviceId =   DeviceInterface.getDeviceId();
//               String deviceId =   DeviceInterface.getDeviceVersion();
//           String deviceId = DeviceInterface.getDeviceSerial();
           Message.siecomproto.Builder msgBuilder = Message.siecomproto.newBuilder();
           msgBuilder.setMsgid(msg.getMsgid());
           msgBuilder.setModule(ConstDefine.OTHER_MODULE);
           msgBuilder.setCmd(ConstDefine.DEVICE_SERIAL_NO_RESPOND);
           msgBuilder.setRespond(deviceId);
           msgBuilder.setError(0);
           Message.siecomproto respondMsg = msgBuilder.build();
           server.sendToRemote(respondMsg);
       };
       threadPool.submit(r);

   }

   public String getAllDeviceInfo(){

        JSONObject jb = new JSONObject();
       try {
           jb.put("SN",Build.SERIAL);
           jb.put("BluetoothMac", BlueServer.getBTAddress());
           jb.put("Module",Build.MODEL);
           jb.put("OS","Android");
           jb.put("OSVersion",Build.VERSION.RELEASE);
           jb.put("appVersion",DeviceInterface.getVersion());
           jb.put("buildDate",Build.DISPLAY.split("_")[1].substring(0,8));
           String dateStr = "20221020";
           if (Build.SERIAL.startsWith("A108P")){
               dateStr = "20" + Build.SERIAL.replace("A108P","").substring(0,6);
           }
           jb.put("ProductionDate",dateStr);
           jb.put("fingerprintType","FIG");  //指纹仪类型（FIG：普通指纹仪；CFG：居民指纹仪；ALL：两者均支持

       } catch (JSONException e) {
           throw new RuntimeException(e);
       }
       return jb.toString();
   }
    /**
     * {“SN”：“移动外设序列号”，“BluetoothMac”：“蓝牙mac地址”，“Module”：“移动外设设备型号”，“OS”：“移动外设操作系统”，
     * “OSVersion”:“操作系统版本号”, “appVersion”:“应用版本号”,“buildDate”：“应用build日期（格式YYYYMMDD，如20190101）”，
     * “ProductionDate”:“出厂日期（YYYYMMDD）”，“fingerprintType”：“指纹仪类型（FIG：普通指纹仪；CFG：居民指纹仪；ALL：两者均支持。返回值示例：CFG）”}
     * @param msg
     */
   private void getDeviceHwVersion(Message.siecomproto msg){
       Runnable r = () -> {
//           String deviceId =   DeviceInterface.getDeviceId();
           String deviceVer =   DeviceInterface.getDeviceVersion();
           deviceVer = deviceVer.replace("A108Plus-V1.0-","");
           Message.siecomproto.Builder msgBuilder = Message.siecomproto.newBuilder();
           msgBuilder.setMsgid(msg.getMsgid());
           msgBuilder.setModule(ConstDefine.OTHER_MODULE);
           msgBuilder.setCmd(ConstDefine.GET_DEVICE_VERSION_RESPOND);
           msgBuilder.setRequest(getAllDeviceInfo()); //新加信息
           msgBuilder.setRespond(deviceVer + "|" + DeviceInterface.getVersion());
           msgBuilder.setError(0);
           Message.siecomproto respondMsg = msgBuilder.build();
           server.sendToRemote(respondMsg);
       };
       threadPool.submit(r);
   }

}
